package com.dennis.client;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Dennis Li
 * @date 2020/8/4 10:11
 */
public class SocketServer {

    public static void server(int port, String message) {

        try (ServerSocket serverSocket = new ServerSocket(port);
             Socket socket = serverSocket.accept();
             InputStream is = socket.getInputStream();
             OutputStream os = socket.getOutputStream()) {
            while (true) {
                os.write(message.getBytes());
                is.read(new byte[1024]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        final int nums = SocketClient.nums;

        final ExecutorService servers = Executors.newFixedThreadPool(nums);

        for (int i = 0; i < nums; i++) {
            final int temp = i;
            servers.submit(() -> {
                try {
                    server(6000 + temp, "Hello world" + temp);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }

}
